package com.jnu.myAccount.fragment;

import static com.jnu.myAccount.MyTextInputWatcher.getStandardDateString;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.textfield.TextInputEditText;
import com.jnu.myAccount.R;
import com.jnu.myAccount.databinding.FragmentInAndOutBinding;
import com.jnu.myAccount.databinding.LayoutDatepickerBinding;
import com.jnu.myAccount.MyTextInputWatcher;
import com.jnu.myAccount.menu.home.HomeViewModel;
import com.jnu.myAccount.record.DataPackage;
import com.jnu.myAccount.record.Record;
import com.jnu.myAccount.viewModel.EditViewModel;

import java.util.Date;

public class InAndOutFragment extends Fragment {
    private EditViewModel editViewModel;

    public FragmentInAndOutBinding getFragmentInAndOutBinding() {
        return fragmentInAndOutBinding;
    }

    private FragmentInAndOutBinding fragmentInAndOutBinding;
    private TextInputEditText textInputEditText;
    private TextView textViewDescribe;
    private RecyclerView recyclerView;
    private Intent intent;
    private DataPackage dataPackage;
    private Record recordNeedToModify;
    public InAndOutFragment() {
        // Required empty public constructor
    }

    //返回收入支出页面的实例
    public static InAndOutFragment newInstance() {
        return new InAndOutFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化编辑窗口数据模块editViewModel和与调用片段的Activity的消息传递组件intent
        editViewModel = new ViewModelProvider(requireActivity()).get(EditViewModel.class);
        dataPackage = DataPackage.Instance();
        intent = requireActivity().getIntent();
        recordNeedToModify=dataPackage.getRecordNeedToModify();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //初始化片段视图的绑定部件Binding和片段布局文件
        fragmentInAndOutBinding = FragmentInAndOutBinding.inflate(inflater, container, false);
        View root = fragmentInAndOutBinding.getRoot();
        //初始化输入金额文本区并设置文本监听器
        textInputEditText = fragmentInAndOutBinding.inputArea;
        textInputEditText.addTextChangedListener(new MyTextInputWatcher(textInputEditText,editViewModel.getFund()));
        if (dataPackage.getNeedModify()){
            HomeViewModel homeViewModel=dataPackage.getHomeViewModel();
            textInputEditText.setText(recordNeedToModify.getFundValue()+"");
            editViewModel.setType(recordNeedToModify.getIndexOfType());
            String[] strings = recordNeedToModify.getDateValue().split("-");
            int year = Integer.parseInt(strings[0]);
            int month = Integer.parseInt(strings[1]);
            int day = Integer.parseInt(strings[2]);
            editViewModel.setDate(year,month,day);
        }

        //使用recyclerView显示消费类型选择区域，设置管理器和适配器
        recyclerView = fragmentInAndOutBinding.recycleViewItem;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(root.getContext(), 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        RecycleViewAdapter recycleViewAdapter = new RecycleViewAdapter();
        recyclerView.setAdapter(recycleViewAdapter);

        //用自定义类封装四个按钮并在监听它们的点击事件
        Buttons buttons=new Buttons(
                fragmentInAndOutBinding.buttonInOut, fragmentInAndOutBinding.buttonAccount,
                fragmentInAndOutBinding.buttonDate, fragmentInAndOutBinding.buttonSave);

        //自定义Listener类监视日期、账户、消费类型和收支等选项的变化
        new Listener(buttons.getDatePicker());


        //返回root渲染视图
        return root;
    }

    //自定义RecyclerView的适配器
    private class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder>
    {
        //记录上次选择的消费类型，-1代表还未选择处于默认状态
        private int preClick = -1;

        public RecycleViewAdapter()
        {
            super();
        }

        @NonNull
        @Override
        //返回用来容纳消费类型的ViewHolder
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_kind_layout,parent,false);
            return new ViewHolder(view);
        }

        @Override
        //将数据与视图绑定
        public void onBindViewHolder(@NonNull RecycleViewAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            //指定消费类型的图标与文字
            holder.getIconView().setImageResource(editViewModel.getKindIcon(position));
            holder.getTextView().setText(editViewModel.getKindText(position));

            //监听点击图标事件，点击后改变图片和文字的颜色
            holder.itemView.setOnClickListener(v -> {
                editViewModel.setType(position);
                holder.iconView.setColorFilter(Color.rgb(160,20,20), PorterDuff.Mode.SRC_IN);
                holder.textView.setTextColor(Color.rgb(160,20,20));
                //若与上次选择的不同则还原颜色
                if(preClick!=-1 && preClick != holder.getAdapterPosition())
                {
                    ImageView img = recyclerView.getChildAt(preClick)
                            .findViewById(R.id.icon_kind_image);
                    TextView textView=recyclerView.getChildAt(preClick)
                            .findViewById(R.id.kind_text);
                    img.clearColorFilter();
                    textView.setTextColor(Color.rgb(0,0,0));
                }
                //更新选择的消费类型
                preClick = holder.getAdapterPosition();
            });

        }

        @Override
        //返回RecyclerView中item的数量
        public int getItemCount() {
            return editViewModel.getKindCount();
        }

        //自定义item的布局类以方便获取其拥有的组件
        private class ViewHolder extends RecyclerView.ViewHolder
        {
            private final ImageView iconView;
            private final TextView textView;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                iconView = itemView.findViewById(R.id.icon_kind_image);
                textView = itemView.findViewById(R.id.kind_text);
            }

            public ImageView getIconView() {
                return iconView;
            }
            public TextView getTextView() {
                return textView;
            }
        }
    }

    public class Buttons
    {
        //定义日期选择器和日期选择窗口
        private DatePicker datePicker;
        private PopupWindow datePickerWindow;

        public Buttons(Button buttonInOut, Button buttonAccount, Button buttonDate, Button buttonSave) {
            //初始化date按钮显示今天的日期和日期选择窗口
            buttonDate.setText(editViewModel.getDate().getValue());
            initDatePickerWindow();

            //点击收支按钮，切换记账模式
            buttonInOut.setOnClickListener(v -> editViewModel.setButtonInOut());

            //点击账户按钮，切换账户
            buttonAccount.setOnClickListener(v -> editViewModel.setButtonAccount());

            //点击日期按钮，打开日期选择器
            buttonDate.setOnClickListener(v -> { datePickerWindow.showAtLocation(v,Gravity.CENTER,0,0); });

            //点击保存按钮，数据模块记录数据保存到本地文件并结束当前Activity
            buttonSave.setOnClickListener(v -> {
                if (dataPackage.getNeedModify()){
                    HomeViewModel homeViewModel=dataPackage.getHomeViewModel();
                    homeViewModel.deleteRecord(dataPackage.getModifyDate(),dataPackage.getModifyPosition());
                    homeViewModel.loadData();
                    editViewModel.modify(recordNeedToModify);
                    dataPackage.addNewRecord(recordNeedToModify);
                    dataPackage.setNeedModify(false);
                }
                else
                    editViewModel.completeFundFlowInfo();
                requireActivity().finish();
            });
        }

        private void initDatePickerWindow() {
            //初始化日期选择器视图的绑定部件
            LayoutDatepickerBinding layoutDatepickerBinding = LayoutDatepickerBinding.inflate(LayoutInflater.from(requireActivity()),
                    null, false);

            //初始化日期选择器的窗口
            datePickerWindow = new PopupWindow(layoutDatepickerBinding.getRoot(),
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

            //初始化日期选择器
            datePicker = layoutDatepickerBinding.datePicker;

            //监听日期选择器中的‘今天’按钮，跳转日期到今天
            layoutDatepickerBinding.buttonToday.setOnClickListener(v -> {
                //获取当前时间
                Date date = new Date(System.currentTimeMillis());

                //对日期切片获取年、月、日
                String[] strings = MyTextInputWatcher.getStandardDateString(date).split("-");
                int year = Integer.parseInt(strings[0]);
                int month = Integer.parseInt(strings[1]) -1;//实际月份需要减一
                int dayOfMonth = Integer.parseInt(strings[2]);

                //更新日期选择器时间
                datePicker.updateDate(year,month,dayOfMonth);
            });

            //监听确定按钮点击事件
            layoutDatepickerBinding.buttonCommit.setOnClickListener(v -> {
                //记录当前日期到数据模块中
                editViewModel.setDate(datePicker.getYear(),datePicker.getMonth()+1,
                        datePicker.getDayOfMonth());
                //关闭日期选择的窗口
                datePickerWindow.dismiss();
            });
        }

        public DatePicker getDatePicker() {
            return datePicker;
        }
    }

    private class Listener {
        //构造函数，监视日期、账户、消费类型和收支类型的变化
        public Listener(DatePicker datePicker) {
            setDateObserver(datePicker);
            setAccountObserver();
            setKindObserver();
            setIsInObserver();
        }

        //设置日期监视器，点击按钮后更新按钮的文本及日期选择器的日期
        public void setDateObserver(DatePicker datePicker)
        {
            editViewModel.getDate().observe(InAndOutFragment.this, (String date) -> {
                fragmentInAndOutBinding.buttonDate.setText(date);
                String[] daySelected = date.split("-");
                datePicker.updateDate(Integer.parseInt(daySelected[0]),
                        Integer.parseInt(daySelected[1])-1,
                        Integer.parseInt(daySelected[2]));
            });
        }

        //设置账户监视器，点击后更新按钮的文本为下一账户
        public void setAccountObserver() {
            editViewModel.getAccount().observe(InAndOutFragment.this, (String s) -> {
                fragmentInAndOutBinding.buttonAccount.setText(s);
            });
        }

        //设置消费类型监视器，点击后更新消费类型的文本为选择的类型
        public void setKindObserver()
        {
            editViewModel.getType().observe(InAndOutFragment.this, (String s) -> {
                fragmentInAndOutBinding.describe.setText(s);
            });
        }

        //设置收入类型监视器
        public void setIsInObserver()
        {
            editViewModel.getInOrOut().observe(InAndOutFragment.this, aBoolean -> {
                //更改收入类型按钮文本
                if (aBoolean)
                    fragmentInAndOutBinding.buttonInOut.setText("收入");
                else
                    fragmentInAndOutBinding.buttonInOut.setText("支出");
            });
        }
    }


}